<template>
  <div class="forgot-password-container">
    <el-card class="forgot-password-card">
      <template #header>
        <h2 class="forgot-password-title">找回密码</h2>
      </template>
      <el-steps :active="currentStep" finish-status="success" simple>
        <el-step title="邮箱验证" />
        <el-step title="重置密码" />
      </el-steps>
      <!-- 步骤1：邮箱验证 -->
      <el-form v-if="currentStep === 0" :model="emailForm" :rules="emailRules" ref="emailFormRef" class="forgot-password-form">
        <el-form-item prop="email">
          <el-input
            v-model="emailForm.email"
            placeholder="请输入注册邮箱"
            prefix-icon="Message"
          />
        </el-form-item>
        <el-form-item prop="verificationCode">
          <div class="verification-container">
            <el-input
              v-model="emailForm.verificationCode"
              placeholder="请输入验证码"
              prefix-icon="Key"
            />
            <el-button
              type="primary"
              :disabled="!!countdown"
              @click="sendVerificationCode"
            >
              {{ countdown ? `${countdown}秒后重试` : '获取验证码' }}
            </el-button>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading" class="submit-button" @click="verifyEmail">
            下一步
          </el-button>
          <el-button class="cancel-button" @click="handleCancel">
            返回登录
          </el-button>
        </el-form-item>
      </el-form>
      <!-- 步骤2：重置密码 -->
      <el-form v-else :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" class="forgot-password-form">
        <el-form-item prop="password">
          <el-input
            v-model="passwordForm.password"
            type="password"
            placeholder="请输入新密码"
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>
        <el-form-item prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            placeholder="请确认新密码"
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading" class="submit-button" @click="resetPassword">
            确认重置
          </el-button>
          <el-button class="cancel-button" @click="handleCancel">
            返回登录
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { sendResetCode, verifyResetCode, resetPassword } from '@/api/user'

const router = useRouter()
const emailFormRef = ref<FormInstance>()
const passwordFormRef = ref<FormInstance>()
const loading = ref(false)
const currentStep = ref(0)
const countdown = ref(0)

const emailForm = reactive({
  email: '',
  verificationCode: ''
})

const passwordForm = reactive({
  password: '',
  confirmPassword: ''
})

const validatePass = (rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== passwordForm.password) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

const emailRules: FormRules = {
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  verificationCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 6, max: 6, message: '验证码长度为6位', trigger: 'blur' }
  ]
}

const passwordRules: FormRules = {
  password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: validatePass, trigger: 'blur' }
  ]
}

const startCountdown = () => {
  countdown.value = 60
  const timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
}

const sendVerificationCode = async () => {
  if (!emailFormRef.value) return
  
  await emailFormRef.value.validateField('email', async (valid) => {
    if (valid) {
      try {
        await sendResetCode(emailForm.email)
        startCountdown()
        ElMessage.success('验证码已发送到您的邮箱')
      } catch (error) {
        ElMessage.error('验证码发送失败，请稍后重试')
      }
    }
  })
}

const verifyEmail = async () => {
  if (!emailFormRef.value) return
  
  await emailFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      loading.value = true
      try {
        await verifyResetCode(emailForm.email, emailForm.verificationCode)
        currentStep.value = 1
      } catch (error) {
        ElMessage.error('验证码验证失败，请检查后重试')
      } finally {
        loading.value = false
      }
    }
  })
}

const resetPassword = async () => {
  if (!passwordFormRef.value) return
  
  await passwordFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      loading.value = true
      try {
        await resetPassword(emailForm.email, passwordForm.password, emailForm.verificationCode)
        ElMessage.success('密码重置成功')
        router.push('/login')
      } catch (error) {
        ElMessage.error('密码重置失败，请稍后重试')
      } finally {
        loading.value = false
      }
    }
  })
}

const handleCancel = () => {
  router.push('/login')
}
</script>

<style lang="scss" scoped>
.forgot-password-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f0f2f5;
}

.forgot-password-card {
  width: 500px;
  
  .forgot-password-title {
    text-align: center;
    margin: 0;
    color: #303133;
  }
}

.forgot-password-form {
  margin-top: 20px;
  
  .verification-container {
    display: flex;
    gap: 12px;
    
    .el-input {
      flex: 1;
    }
  }
  
  .submit-button {
    width: 45%;
  }
  
  .cancel-button {
    width: 45%;
    margin-left: 10%;
  }
}

.el-steps {
  margin: 20px 0;
}
</style>